<template>
  <div class="video-player-container">
    <!-- 顶部导航 -->
    <div class="player-header">
      <el-page-header @back="goBack" :content="`正在播放: ${videoInfo.courseName} - ${videoInfo.chapterTitle}`" />
    </div>
    
    <!-- 主播放区 -->
    <div class="player-main">
      <!-- 已完成提示 -->
      <div class="completed-prompt" v-if="showCompletedPrompt">
        <el-alert
          title="您已看完本视频"
          type="success"
          show-icon
          :closable="false"
        >
          <el-button type="primary" size="small" @click="replayVideo">
            <el-icon><Refresh /></el-icon> 重新观看
          </el-button>
        </el-alert>
      </div>
      
      <!-- 恢复播放提示 -->
      <div class="resume-prompt" v-if="showResumePrompt && !showCompletedPrompt">
        <el-alert 
          title="检测到您有未看完的进度"
          type="info"
          show-icon
          :closable="false"
        >
          <el-button type="primary" size="small" @click="resumeFromLastPosition">
            从上次位置继续 ({{ formatDuration(savedProgress) }})
          </el-button>
          <el-button size="small" @click="startFromBeginning">
            重新开始
          </el-button>
        </el-alert>
      </div>
      
      <div class="video-wrapper">
        <video
          ref="videoPlayer"
          class="video-js vjs-big-play-centered"
          controls
          preload="auto"
          :poster="videoInfo.coverUrl || defaultCover"
        >
          <source :src="videoSource" type="video/mp4">
          <p class="vjs-no-js">
            您的浏览器不支持HTML5视频，请升级浏览器
          </p>
        </video>
        <el-button 
          v-if="!isPlaying && showPlayButton"
          class="play-button"
          type="primary"
          circle
          @click="startPlayback"
        >
          <el-icon><VideoPlay /></el-icon>
        </el-button>
      </div>
      
      <!-- 进度信息区 -->
      <div class="progress-info" v-if="videoInfo.duration > 0 && studentId">
        <el-progress 
          :percentage="progressPercentage" 
          :format="formatProgress" 
          :stroke-width="16"
          :color="progressColor"
        />
        <div class="progress-meta">
          <span>已观看: {{ formatDuration(currentProgress) }} / {{ formatDuration(videoInfo.duration) }}</span>
          <el-tag 
            :type="isCompleted ? 'success' : progressStatusType"
            :class="{ 'completed-tag': isCompleted }"
          >
            <el-icon v-if="isCompleted"><CircleCheck /></el-icon>
            {{ isCompleted ? '已看完' : progressStatusText }}
          </el-tag>
        </div>
      </div>
      
      <!-- 本地文件选择按钮 -->
      <div class="local-file-selector" v-if="showLocalFileSelector">
        <el-button type="primary" @click="selectLocalFile">
          <el-icon><Upload /></el-icon>选择本地MP4文件
        </el-button>
      </div>
      
      <!-- 视频信息区 -->
      <div class="video-info">
        <h2>{{ videoInfo.chapterTitle }}</h2>
        <div class="video-meta">
          <span><i class="el-icon-time"></i> 时长: {{ formatDuration(videoInfo.duration) }}</span>
          <span><i class="el-icon-view"></i> 播放量: {{ videoInfo.viewCount || 0 }}</span>
          <span><i class="el-icon-date"></i> 更新时间: {{ formatDate(videoInfo.updateTime) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import { ElMessage, ElLoading } from 'element-plus'
import { Upload, VideoPlay, Refresh, CircleCheck } from '@element-plus/icons-vue'
import { courseApi } from '@/api/course'
import { studentApi } from '@/api/students'
import defaultCover from '@/assets/fault.png'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const videoPlayer = ref(null)
let player = null

// 响应式数据
const videoSource = ref('')
const showLocalFileSelector = ref(false)
const currentProgress = ref(0)
const savedProgress = ref(0)
const lastSaveTime = ref(0)
const isPlaying = ref(false)
const studentId = ref(null)
const showResumePrompt = ref(false)
const showCompletedPrompt = ref(false)
const showPlayButton = ref(true)
const isPageVisible = ref(true)
const isCompleted = ref(false)

// 视频信息
const videoInfo = ref({
  courseId: '',
  courseName: '',
  chapterId: '',
  chapterTitle: '',
  videoUrl: '',
  coverUrl: '',
  duration: 0,
  viewCount: 0,
  updateTime: ''
})

// 计算属性
const progressPercentage = computed(() => {
  if (!videoInfo.value.duration) return 0
  return Math.min(100, (currentProgress.value / videoInfo.value.duration) * 100)
})

const progressStatusType = computed(() => {
  if (progressPercentage.value >= 90) return 'success'
  if (progressPercentage.value >= 50) return 'warning'
  return 'info'
})

const progressStatusText = computed(() => {
  if (isCompleted.value) return '已看完'
  if (progressPercentage.value >= 90) return '几乎看完'
  if (progressPercentage.value >= 50) return '观看中'
  return '刚开始'
})

const progressColor = computed(() => {
  return [
    { color: '#67C23A', percentage: 90 },
    { color: '#E6A23C', percentage: 50 },
    { color: '#409EFF', percentage: 0 }
  ]
})

// 检查是否是本地路径
const isLocalPath = (url) => {
  return url?.startsWith('file://') || /^[a-zA-Z]:\\/.test(url)
}

// 处理页面可见性变化
const handleVisibilityChange = () => {
  isPageVisible.value = !document.hidden
  if (!isPageVisible.value && player) {
    player.pause()
    if (isPlaying.value) {
      saveProgress()
    }
  }
}

// 获取可靠的备用视频URL
const getFallbackVideoUrl = () => {
  const fallbackUrls = [
    'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
    'https://sample-videos.com/video123/mp4/480/big_buck_bunny_480p_1mb.mp4'
  ]
  return fallbackUrls.find(url => {
    try { new URL(url); return true } 
    catch { return false }
  })
}

// 获取进度信息
// 获取进度信息 - 添加详细日志
// 修改后的fetchProgress方法
const fetchProgress = async () => {
  if (!studentId.value || !videoInfo.value.courseId || !videoInfo.value.chapterId) {
    console.error('缺少必要参数')
    return false
  }

  try {
    console.log('请求进度参数:', {
      studentId: studentId.value,
      courseId: videoInfo.value.courseId,
      chapterId: videoInfo.value.chapterId
    })
    
    const response = await request.get('/api/learning-progress/chapter', {
      params: {
        studentId: Number(studentId.value),
        courseId: Number(videoInfo.value.courseId),
        chapterId: Number(videoInfo.value.chapterId)
      }
    })

    console.log('完整进度响应:', response)
    
    // 处理不同响应格式
    const progressData = response.data?.data || response.data || response
    if (progressData) {
      console.log('解析进度数据:', progressData)
      
      // 兼容不同字段名
      const progress = progressData.mediaProgress || progressData.progress || 0
      const duration = progressData.mediaDuration || videoInfo.value.duration || 0
      
      isCompleted.value = progressData.learnedStatus === 1
      savedProgress.value = isCompleted.value ? duration : Number(progress) || 0
      
      console.log('最终进度值:', {
        isCompleted: isCompleted.value,
        savedProgress: savedProgress.value,
        duration: duration
      })
      
      updateProgressUI()
      return true
    }
    return false
  } catch (error) {
    console.error('获取进度失败:', error)
    isCompleted.value = false
    savedProgress.value = 0
    return false
  }
}

// 更新UI状态
const updateProgressUI = () => {
  showCompletedPrompt.value = isCompleted.value
  showResumePrompt.value = !isCompleted.value && savedProgress.value > 0
}

// 开始播放
const startPlayback = async () => {
  if (!player) return
  
  try {
    videoPlayer.value.scrollIntoView({ behavior: 'smooth', block: 'center' })
    await new Promise(resolve => setTimeout(resolve, 300))
    
    await player.play()
    isPlaying.value = true
    showPlayButton.value = false
    
    // 如果是已完成的视频，从头开始播放
    if (isCompleted.value) {
      player.currentTime(0)
      isCompleted.value = false
      showCompletedPrompt.value = false
    }
  } catch (error) {
    console.error('播放失败:', error)
    ElMessage.error('播放失败，请点击播放按钮重试')
    showPlayButton.value = true
  }
}

// 从上次位置继续播放
const resumeFromLastPosition = () => {
  if (player) {
    player.currentTime(savedProgress.value)
    startPlayback()
    showResumePrompt.value = false
  }
}

// 重新开始播放
const startFromBeginning = () => {
  if (player) {
    player.currentTime(0)
    currentProgress.value = 0
    savedProgress.value = 0
    isCompleted.value = false
    showCompletedPrompt.value = false
    startPlayback()
    showResumePrompt.value = false
    saveProgress() // 重置进度
  }
}

// 重新观看视频
const replayVideo = () => {
  if (player) {
    player.currentTime(0)
    isCompleted.value = false
    showCompletedPrompt.value = false
    startPlayback()
  }
}



// 保存进度到后端
// 修改后的saveProgress方法
const saveProgress = async (isCompletedFlag = false) => {
  if (!studentId.value || !videoInfo.value.courseId || !videoInfo.value.chapterId) {
    console.warn('无法保存进度:缺少必要参数')
    return false
  }

  const payload = {
    studentId: studentId.value,
    courseId: videoInfo.value.courseId,
    chapterId: videoInfo.value.chapterId,
    currentPosition: Math.round(currentProgress.value),
    totalDuration: Math.round(videoInfo.value.duration),
    learnedStatus: isCompletedFlag ? 1 : 0
  }

  try {
    console.log('保存进度请求:', payload)
    const response = await request({
      method: 'POST',
      url: '/api/learning-progress/update',
      data: payload,
      headers: {
        'Content-Type': 'application/json'
      }
    })

    console.log('保存进度响应:', response)
    
    // 处理不同响应格式
    const success = response?.data?.success ?? response?.success ?? true
    if (success !== false) {
      if (isCompletedFlag) {
        isCompleted.value = true
        savedProgress.value = videoInfo.value.duration
      }
      return true
    }
    
    throw new Error('进度保存失败')
  } catch (error) {
    console.error('保存进度错误:', error)
    return false
  }
}

// 获取学生ID
const fetchStudentId = async () => {
  try {
    if (!authStore.userId) {
      throw new Error('用户未登录，请先登录')
    }
    
    const response = await studentApi.getStudentIdByUserId(authStore.userId)
    
    if (!response) {
      throw new Error('获取学生ID失败: 无响应')
    }

    if (response.data !== undefined) {
      studentId.value = response.data
    } else if (response.result !== undefined) {
      studentId.value = response.result
    } else {
      throw new Error('获取学生ID失败: 响应格式不匹配')
    }
    
    return true
  } catch (err) {
    console.error('获取学生ID失败:', err)
    ElMessage.error('获取学生信息失败: ' + (err.response?.data?.message || err.message || '未知错误'))
    return false
  }
}

// 获取视频信息
// 在fetchVideoInfo中添加日志
// 修改后的fetchVideoInfo函数
const fetchVideoInfo = async () => {
  const loading = ElLoading.service({ lock: true })
  
  try {
    console.log('开始获取视频信息')
    const { courseId, chapterId, videoUrl } = route.query
    if (!courseId || !chapterId) throw new Error('缺少必要参数')

    console.log('路由参数:', { courseId, chapterId, videoUrl })
    
    videoInfo.value = {
      courseId,
      chapterId,
      videoUrl: videoUrl || '',
      courseName: '加载中...',
      chapterTitle: '加载中...',
      coverUrl: defaultCover,
      duration: 0,
      viewCount: 0,
      updateTime: ''
    }

    // 检查是否有传递学生ID
    if (authStore.userId) {
      console.log('开始获取学生ID')
      if (!await fetchStudentId()) {
        console.log('获取学生ID失败，将不记录进度')
      } else {
        console.log('学生ID获取成功:', studentId.value)
        // 检查学习进度
        console.log('开始检查学习进度')
        await fetchProgress()
        console.log('进度检查完成', {
          isCompleted: isCompleted.value,
          savedProgress: savedProgress.value
        })
      }
    } else {
      console.log('未登录用户，将不记录进度')
    }

    // 获取视频详细信息
    console.log('开始获取视频详细信息')
    const { data } = await courseApi.getVideoInfo(courseId, chapterId)
    console.log('视频详细信息响应:', data)
    
    Object.assign(videoInfo.value, {
      courseName: data.courseName || '未知课程',
      chapterTitle: data.chapterTitle || '未知章节',
      coverUrl: data.coverUrl || defaultCover,
      duration: Number(data.duration) || 0,
      viewCount: Number(data.viewCount) || 0,
      updateTime: data.updateTime || ''
    })

    console.log('视频信息更新完成:', videoInfo.value)

    // 初始化播放器
    console.log('开始初始化播放器')
    videoSource.value = videoInfo.value.videoUrl || getFallbackVideoUrl()
    console.log('视频源:', videoSource.value)
    await initPlayer()
    console.log('播放器初始化完成')

  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error(`加载失败: ${error.message}`)
    // 降级处理
    videoSource.value = getFallbackVideoUrl()
    await initPlayer()
  } finally {
    loading.close()
  }
}

// 修改后的initPlayer函数
const initPlayer = async () => {
  console.log('开始初始化播放器，当前进度状态:', {
    isCompleted: isCompleted.value,
    savedProgress: savedProgress.value,
    duration: videoInfo.value.duration,
    hasStudentId: !!studentId.value
  })
  
  if (player) {
    console.log('清理现有播放器实例')
    player.dispose()
    player = null
  }

  player = videojs(videoPlayer.value, {
    controls: true,
    autoplay: false,
    fluid: true,
    techOrder: ['html5'],
    sources: [{
      src: videoSource.value,
      type: 'video/mp4'
    }]
  })

  // 元数据加载
  player.on('loadedmetadata', () => {
    console.log('视频元数据加载完成')
    videoInfo.value.duration = player.duration() !== Infinity 
      ? Math.floor(player.duration()) 
      : 600
    
    console.log('视频时长:', videoInfo.value.duration)
    
    // 只有有学生ID时才处理进度
    if (studentId.value) {
      if (isCompleted.value) {
        console.log('视频已看完，重置到开头')
        player.currentTime(0)
      } else if (savedProgress.value > 0) {
        console.log('从保存的进度继续:', savedProgress.value)
        player.currentTime(savedProgress.value)
      } else {
        console.log('没有保存的进度，从头开始')
      }
      updateProgressUI()
    } else {
      console.log('无学生ID，直接从头开始播放')
      player.currentTime(0)
    }
    
    showPlayButton.value = true
  })

  // 只有有学生ID时才监听进度
  if (studentId.value) {
    player.on('timeupdate', handleTimeUpdate)
    player.on('ended', handleVideoEnded)
  }
  
  player.on('play', () => {
    isPlaying.value = true
    showPlayButton.value = false
  })
  player.on('pause', () => {
    isPlaying.value = false
    showPlayButton.value = true
  })

  player.on('error', () => {
    if (isLocalPath(videoSource.value)) {
      ElMessage.warning('浏览器无法直接播放本地视频，请使用文件选择器')
      showLocalFileSelector.value = true
    } else {
      ElMessage.error('视频加载失败，正在尝试备用源...')
      videoSource.value = getFallbackVideoUrl()
      player.src({ type: 'video/mp4', src: videoSource.value })
      player.load()
    }
  })
}

// 修改后的handleTimeUpdate函数
const handleTimeUpdate = () => {
  if (!player || !isPageVisible.value || !studentId.value) return
  
  currentProgress.value = player.currentTime()
  
  const now = Date.now()
  if (now - lastSaveTime.value > 5000 || 
      Math.abs(currentProgress.value - savedProgress.value) > 30) {
    saveProgress()
    lastSaveTime.value = now
    savedProgress.value = currentProgress.value
  }
}

// 修改后的handleVideoEnded函数
const handleVideoEnded = () => {
  if (!studentId.value) return
  
  currentProgress.value = videoInfo.value.duration
  isCompleted.value = true
  showCompletedPrompt.value = true
  saveProgress(true)
}

// 选择本地文件
const selectLocalFile = () => {
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = 'video/mp4'
  
  fileInput.onchange = (e) => {
    const file = e.target.files[0]
    if (!file) return

    if (!file.type.includes('mp4')) {
      ElMessage.error('请选择MP4格式视频')
      return
    }

    videoSource.value = URL.createObjectURL(file)
    videoInfo.value.chapterTitle = file.name
    initPlayer()
  }
  
  fileInput.click()
}

// 格式化工具函数
const formatDate = (dateStr) => dateStr ? new Date(dateStr).toLocaleDateString() : ''
const formatDuration = (seconds) => {
  if (!seconds) return '00:00'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  return `${h > 0 ? h + ':' : ''}${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`
}
const formatProgress = () => `${progressPercentage.value.toFixed(1)}%`

// 返回
const goBack = () => {
  if (player && isPlaying.value) {
    saveProgress()
  }
  router.back()
}

onMounted(async () => {
  document.addEventListener('visibilitychange', handleVisibilityChange)
  await fetchVideoInfo()
})

onBeforeUnmount(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  
  if (player && isPlaying.value) {
    saveProgress()
  }
  if (videoSource.value.startsWith('blob:')) {
    URL.revokeObjectURL(videoSource.value)
  }
  if (player) player.dispose()
})
</script>

<style scoped>
.video-player-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f7fa;
}

.player-header {
  margin-bottom: 20px;
}

.player-main {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.completed-prompt,
.resume-prompt {
  margin: 10px 20px;
  text-align: center;
}

.video-wrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 比例 */
  height: 0;
  overflow: hidden;
}

.video-wrapper video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  width: 60px;
  height: 60px;
  font-size: 24px;
}

.progress-info {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.progress-meta {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.completed-tag .el-icon {
  margin-right: 5px;
}

.local-file-selector {
  text-align: center;
  padding: 15px 0;
}

.video-info {
  padding: 20px;
}

.video-info h2 {
  margin: 0 0 10px 0;
  font-size: 22px;
  color: #333;
}

.video-meta {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
}

.video-meta i {
  margin-right: 5px;
}

/* 视频播放器自定义样式 */
:deep(.video-js) {
  width: 100%;
  height: 100%;
}

:deep(.vjs-big-play-button) {
  background-color: rgba(64, 158, 255, 0.8);
  border: none;
  width: 3em;
  height: 3em;
  line-height: 3em;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

:deep(.vjs-control-bar) {
  background-color: rgba(0, 0, 0, 0.7);
}

:deep(.vjs-play-progress) {
  background-color: #409eff;
}

:deep(.vjs-play-progress:before) {
  font-size: 1em;
  top: -0.3em;
}
</style>